package com.ruoyi.web.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.enums.AbnormalEnum;
import com.ruoyi.framework.web.exception.TadpoleException;
import com.ruoyi.web.domain.AppUser;
import com.ruoyi.web.domain.EmailTemplate;
import com.ruoyi.web.dto.SendEmailDTO;
import com.ruoyi.web.enums.UserEnums;
import com.ruoyi.web.mapper.AppUserMapper;
import com.ruoyi.web.mapper.EmailTemplateMapper;
import com.ruoyi.web.utils.EmailUtil;
import com.ruoyi.web.vo.EmailInformationVO;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 13596
 */
@RestController
@RequestMapping("/email")
@AllArgsConstructor
public class EmailController {

    private final EmailTemplateMapper templateMapper;
    private final EmailUtil emailUtil;
    private final AppUserMapper appUserMapper;
    private final StringRedisTemplate redisTemplate;

    @Anonymous
    @PostMapping("/send")
    public R<String> sendEmail(@RequestBody SendEmailDTO dto) {
        Long userId = SecurityUtils.getUserId();
        AppUser appUser = appUserMapper.selectAppUserById(userId);
        if (appUser == null) {
            throw new TadpoleException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
        }
        Map<String, String> textContentCode = new HashMap<>();
        Map<String, String> titleCode = new HashMap<>();
        // 确认提现
        if (dto.getType().equals(UserEnums.EmailType.Withdrawal_Request.getValue())) {
            if (dto.getWithdrawalEmail() == null) {
                throw new TadpoleException(AbnormalEnum.MSG.MANDATORY_PARAM_EMPTY_OR_MALFORMED.getCode(),"Confirm that the withdrawal parameter is blank");
            }
            textContentCode.put("${actualWithdrawalAmount}",dto.getWithdrawalEmail().getActualWithdrawalAmount().toPlainString());
            textContentCode.put("${arrivalAddress}",dto.getWithdrawalEmail().getArrivalAddress());
        }
        // 查询模板
        List<EmailTemplate> templates = templateMapper.selectEmailTemplateList(new EmailTemplate() {{
            setType(UserEnums.EmailType.findType(dto.getType()));
        }});
        EmailTemplate template = templates.size() > 0 ? templates.get(0) : null;
        if (template == null) {
            throw new TadpoleException(AbnormalEnum.MSG.SERVICE_SHUTTING_DOWN.getCode(),"The mailbox template does not exist");
        }
        // 标题时间
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateStr = LocalDateTime.now().format(format);
        titleCode.put("#{time}",dateStr);
        // 六位随机数验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        // 邮件内容中替换的参数
        textContentCode.put("${code}",code);
        R email = emailUtil.sendEmail(titleCode, textContentCode, dto.getEmail() == null ? appUser.getEmail() : dto.getEmail(), new EmailInformationVO() {{
            setTitle(template.getTitle());
            setTextContent(template.getTextContent());
        }});
        if (email.getCode() == HttpStatus.SUCCESS) {
            //向redis里存入数据和设置缓存时间
            redisTemplate.opsForValue().set(
                    (dto.getEmail() == null ? appUser.getEmail() : dto.getEmail()) + " massage = " + UserEnums.EmailType.findType(dto.getType()),
                    code, 60 * 3, TimeUnit.SECONDS);
            return R.ok();
        } else {
            return R.fail();
        }
    }

}
